package com.beatingapp;

import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;

import org.andengine.engine.camera.Camera;
import org.andengine.engine.camera.hud.controls.AnalogOnScreenControl;
import org.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener;
import org.andengine.engine.camera.hud.controls.BaseOnScreenControl;
import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.engine.handler.physics.PhysicsHandler;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.modifier.PathModifier;
import org.andengine.entity.modifier.PathModifier.Path;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.AnimatedSprite;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.util.FPSLogger;
import org.andengine.input.touch.TouchEvent;
import org.andengine.input.touch.controller.MultiTouch;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.ITiledTextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import org.andengine.ui.activity.SimpleBaseGameActivity;

import android.content.Intent;
import android.opengl.GLES20;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

/**
 * (c) 2010 Nicolas Gramlich
 * (c) 2011 Zynga
 *
 * @author Nicolas Gramlich
 * @since 00:06:23 - 11.07.2010
 */
public class CollisionDetectionExample extends SimpleBaseGameActivity implements IOnSceneTouchListener {
	// ===========================================================
	// Constants
	// ===========================================================

	private static final int CAMERA_WIDTH = 800;
	private static final int CAMERA_HEIGHT = 480;

	// ===========================================================
	// Fields
	// ===========================================================

	private Camera mCamera;

	private BitmapTextureAtlas mBitmapTextureAtlas;
	private BitmapTextureAtlas mBitmapTextureAtlas2;
	private BitmapTextureAtlas mBitmapTextureAtlasPelo;
	private BitmapTextureAtlas fondoTexture;
	private BitmapTextureAtlas BarraTiempoTextureAtlas;
	private BitmapTextureAtlas infoTextureAtlas;


	private ITextureRegion fondo;
	private ITextureRegion BarraTiempo;

	private ITiledTextureRegion espalda;
	private ITiledTextureRegion pelo;
	private ITextureRegion manos;
	private ITextureRegion gano;
	private BitmapTextureAtlas mOnScreenControlTexture;
	private ITextureRegion mOnScreenControlBaseTextureRegion;
	private ITextureRegion mOnScreenControlKnobTextureRegion;
	private boolean masajeador, yaGano;
	private long empiezaMasaje;
	private float lastX, lastY;
	private int tiempoTotal;
	private AnalogOnScreenControl velocityOnScreenControl;
	private boolean aux;
	private Path Tiempo;
	private PathModifier pathModifier;
	private Sprite BarraSprite;
	private boolean mPlaceOnScreenControlsAtDifferentVerticalLocations = false;

	// ===========================================================
	// Constructors
	// ===========================================================

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	@Override
	public EngineOptions onCreateEngineOptions() {
		this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);

		final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera);
		engineOptions.getTouchOptions().setNeedsMultiTouch(true);

		if(MultiTouch.isSupported(this)) {
			if(MultiTouch.isSupportedDistinct(this)) {
				Toast.makeText(this, "Masajea por 5 segundos el cabello", Toast.LENGTH_SHORT).show();
			} else {
				this.mPlaceOnScreenControlsAtDifferentVerticalLocations = true;
				Toast.makeText(this, "MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show();
			}
		} else {
			Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show();
		}

		return engineOptions;
	}

	@Override
	public void onCreateResources() {

		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
		this.fondoTexture = new BitmapTextureAtlas( this.getTextureManager( ), 1024, 512 );
		
		this.fondo = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				this.fondoTexture, this, "fondo-dos.jpg", 0, 0 );
		this.BarraTiempoTextureAtlas = new BitmapTextureAtlas( this.getTextureManager( ), 1024, 512 );
		BarraTiempo=BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.BarraTiempoTextureAtlas, this, "barra.png", 0, 0);
		infoTextureAtlas = new BitmapTextureAtlas( getTextureManager( ), 800, 480 );
		this.mBitmapTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 786, 1423, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mBitmapTextureAtlas2= new BitmapTextureAtlas(this.getTextureManager(), 1024, 512, TextureOptions.BILINEAR);
		this.mBitmapTextureAtlasPelo= new BitmapTextureAtlas(this.getTextureManager(), 690, 1822, TextureOptions.BILINEAR);

		//this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0);
		this.manos = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas2, this, "Mano.png", 50, 50);
		this.espalda = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(mBitmapTextureAtlas, this,"matriz_personaje.png", 0, 0, 6, 4);
		this.pelo = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(mBitmapTextureAtlasPelo, this,"pelito2.png", 0, 0, 4, 9);

		this.gano= BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.infoTextureAtlas, this, "fin.png", 0, 0);
		this.mBitmapTextureAtlas.load();
		this.mBitmapTextureAtlas2.load();
		this.mBitmapTextureAtlasPelo.load();
		this.fondoTexture.load( );
		this.infoTextureAtlas.load();
		this.BarraTiempoTextureAtlas.load();
		this.mOnScreenControlTexture = new BitmapTextureAtlas(this.getTextureManager(), 256, 128, TextureOptions.BILINEAR);
		this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0);
		this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0);
		this.mOnScreenControlTexture.load();

	}

	@Override
	public Scene onCreateScene() {

		this.mEngine.registerUpdateHandler(new FPSLogger());
		aux = true;
		final Scene scene = new Scene();
		scene.setOnSceneTouchListener(this);

		/* Create A spinning rectangle and a line. */
		final Sprite ganoSprite = new Sprite( 0, 0, gano, new VertexBufferObjectManager( ) );

		Sprite fondoSprite = new Sprite( 0, 0, fondo, new VertexBufferObjectManager( ) );
		
		final Sprite manos = new Sprite(100, 100, this.manos, this.getVertexBufferObjectManager());
		final AnimatedSprite espalda = new AnimatedSprite(400, 230, this.espalda, this.getVertexBufferObjectManager());
		final AnimatedSprite pelo = new AnimatedSprite(430, 245, this.pelo, this.getVertexBufferObjectManager());
		BarraSprite = new Sprite (0,0, this.BarraTiempo, this.getVertexBufferObjectManager());
		Tiempo = new Path( 2 ).to(-800, 0).to(0, 0);		
		pathModifier = new PathModifier( 13.5f, Tiempo);
		BarraSprite.registerEntityModifier( pathModifier );			
		final long [] duracion = new long[36];
		Arrays.fill(duracion, 90);
		espalda.setScale(2);
		espalda.animate( 100 );
		pelo.setScale(2.5f);
		pelo.animate(0,0);


		//scene.attachChild(face);
		final PhysicsHandler physicsHandler = new PhysicsHandler(manos);
		scene.attachChild(fondoSprite);
		scene.attachChild(espalda);
		scene.attachChild(pelo);
		scene.attachChild(manos);
		scene.attachChild(ganoSprite);
		scene.attachChild(BarraSprite);
		ganoSprite.setVisible(false);
		manos.registerUpdateHandler(physicsHandler);

		/* Velocity control (left). */
		final float x1 = 0;
		final float y1 = CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight();
		velocityOnScreenControl = new AnalogOnScreenControl(x1, y1, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.5f, this.getVertexBufferObjectManager(), new IAnalogOnScreenControlListener() {
			@Override
			public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) {
				physicsHandler.setVelocity(pValueX * 100, pValueY * 100);
				tiempoTotal +=500;
				if(!yaGano && masajeador && (lastX != manos.getX() || lastY != manos.getY())) 
				{
					empiezaMasaje += 500;
					pelo.animate(duracion, 0, 35, true);
					if(empiezaMasaje >= 5000) 
					{
						yaGano = true;		

						Timer t = new Timer();  

						TimerTask task = new TimerTask() {  

							@Override  
							public void run() {  
								runOnUiThread(new Runnable() {  

									@Override  
									public void run() 
									{  		      
										if(aux)
										{
											try 
											{
												crearEscenaFin();
												BarraSprite.setVisible(false);
												ganoSprite.setVisible(true);
												Log.i("jessica", "gano");
												Thread.sleep(5000);
												Intent intent = new Intent(CollisionDetectionExample.this, IntroActivity.class);
												int vidas = getIntent().getExtras().getInt("Vidas");
												Bundle b = new Bundle( );
												b.putInt( "Actividad", 3 );
												b.putInt("Vidas", vidas);
												intent.putExtras( b );
												Log.e("INICIA CIGARRILLOOOO", "INICIA CIGARRILLOOOO EN GANO");
												startActivity(intent);
												CollisionDetectionExample.this.finish();
											} 
											catch (InterruptedException e) {}
											aux = false;
										}
									}  
								});  
							}  
						};  

						t.scheduleAtFixedRate(task, 0, 1000);	
					}
				} 
				else 
				{
					empiezaMasaje = 0;
					pelo.animate(0,0);
				}

				if( tiempoTotal > 13000 && !yaGano )
				{	
					Timer t = new Timer();  

					TimerTask task = new TimerTask() {  

						@Override  
						public void run() {  
							runOnUiThread(new Runnable() {  

								@Override  
								public void run() 
								{  		      
									if( aux )
									{
										try 
										{
											crearEscenaFin();
											ganoSprite.setVisible(true);
											Log.i("jessica", "perdio");
											Thread.sleep(5000);
											Intent intent = new Intent(CollisionDetectionExample.this, IntroActivity.class);
											int vidas = getIntent().getExtras().getInt("Vidas");
											vidas--;
											Bundle b = new Bundle( );
											b.putInt( "Actividad", 3 );
											b.putInt("Vidas", vidas);
											intent.putExtras( b );
											Log.e("INICIA CIGARRILLOOOO", "INICIA CIGARRILLOOOO EN GANO");
											startActivity(intent);
											CollisionDetectionExample.this.finish();
										} 
										catch (InterruptedException e) {}
										aux = false;
									}
								}  
							});  
						}  
					};  

					t.scheduleAtFixedRate(task, 0, 1000);

					Log.i("jessica", "perdio");
				}
				lastX = manos.getX();
				lastY = manos.getY();
			}

			@Override
			public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) {
			}
		});
		velocityOnScreenControl.getControlBase().setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
		velocityOnScreenControl.getControlBase().setAlpha(0.5f);

		scene.setChildScene(velocityOnScreenControl);

		//velocityOnScreenControl.setVisible(false);

		/* The actual collision-checking. */
		manos.registerUpdateHandler(new IUpdateHandler() {
			@Override
			public void reset() { }

			@Override
			public void onUpdate(final float pSecondsElapsed) 
			{
				masajeador=manos.collidesWith(pelo);
				
			}
		});

		return scene;
		}

	@Override
	public boolean onSceneTouchEvent(Scene arg0, TouchEvent arg1) {
		//		Log.i("jessica", "jessica esta relajada x el masaje");
		//		if (arg1.isActionDown()){
		//			if (masajeador)
		//				empiezaMasaje=System.currentTimeMillis();
		//		}else if (arg1.isActionUp()){
		//			empiezaMasaje=0;			
		//		}else if(masajeador && System.currentTimeMillis()-empiezaMasaje > 5000){
		//			runOnUiThread(new Runnable() {
		//
		//				@Override
		//				public void run() {
		//					Toast.makeText(getApplicationContext(), "Gano", Toast.LENGTH_SHORT).show();
		//				}
		//			});
		//
		//		}

		return true;
	}
	
	@SuppressWarnings("unused")
	private void crearEscenaFin (){
		velocityOnScreenControl.setVisible(false);
		BarraSprite.setVisible(false);
	}
}
